/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.andersen.web.validating;

import com.andersen.web.beans.ComponentCommandForm;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;

/**
 *
 * @author Corvus 11
 */
@Component
public class ComponentPropertiesValidator extends AbstractValidator{

    @Override
    public boolean supports(Class type) {
        return ComponentCommandForm.class.isAssignableFrom(type);
    }

    @Override
    public void validate(Object obj, Errors errors) {
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "description", "required.description", "Field is required.");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "serial", "required.serial", "Field is required.");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "typeId", "required.typeId", "Field is required.");
        
        ComponentCommandForm fmt = (ComponentCommandForm)obj;
        
        if (fmt.getSerial().matches("^.*[^A-Z0-9].*$")) {
            errors.rejectValue("serial", "incorrect.serial");
        }
        
        SimpleDateFormat dateFormat = new SimpleDateFormat("dd.MM.yyyy");
        Date today = Calendar.getInstance().getTime();
        
        if (!fmt.getBuyDateString().isEmpty()) {
            try {
                Date dat = dateFormat.parse(fmt.getBuyDateString());
                if (dat.after(today))
                    errors.rejectValue("buyDateString", "notmatch.buyDate");
            } catch (ParseException ex) {
                errors.rejectValue("buyDateString", "incorrect.buyDate");
            }
        }
        
        if (!fmt.getWarrantyEndDateString().isEmpty()) {
            try {
                Date dat = dateFormat.parse(fmt.getWarrantyEndDateString());
            } catch (ParseException ex) {
                errors.rejectValue("warrantyEndDateString", "incorrect.warrantyEndDate");
            }
        }
    }
    
}
